<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pricecontrol extends CI_Controller{

	public function index()
	{
		$this->load->library('session');
		$this->load->helper('form');
		$this->load->model('product');
		$this->load->model('promotion');
		
		
		$dataa = array();
		$in = 0;
		foreach($this->product->getProduct() as $prod)
		{
			$pro['name'] = $prod->name;
			$pro['price'] = $prod->price;
			$pro['id'] = $prod->id;
			$dataa[$in] = $pro;
			$in++;
		}
		$promo;
		$sel[0] ="";
		
		foreach($this->promotion->getPromotion() as $prod)
		{
			
			$x = $this->promotion->getSelectedFor($prod->id);
				if(@$x[0]->promotion_id > 0)
					$sel[$prod->id] = @$x[0]->promotion_id;
				else 
					$sel[$prod->id] = 0;	
			
			$promo[$prod->id] = $prod->name;
		}
		
		$data['prods'] = $dataa;

		$data['selected'] = $sel;
		$data['promo'] = $promo;
		$this->load->view('price', $data);
		
	}
	
	public function process()
	{
		$this->load->model('product');
		$this->load->helper('url');
		$this->load->helper('form');
		
		//update the product
		$this->db->set('price', $_POST['price']);
		$this->db->where("id", $_POST['id']);
		$this->db->update('product');
		
		//if promotion set 
		if($_POST['promotion'] != "")
		{
			$query = $this->db->get_where('shop-promotion-product', array('product_id'=>$_POST['id']), 1, 0);
			$record = array('shop_id' =>1, 'promotion_id' => $_POST['promotion'], 'product_id' => $_POST['id']);
			if ($query->num_rows() == 0) {
			  // A record does not exist, insert one.
			  $query = $this->db->insert('shop-promotion-product', $record);
			} else {
			  // A record does exist, update it.
			  $query = $this->db->update('shop-promotion-product', $record, array('product_id'=>$_POST['id']));
			}
		}
		
		redirect('/pricecontrol/', 'refresh');
	}
}

